package com.blaze.framework.starter.mybatis.plus.util;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blaze.framework.core.util.exception.CheckedException;
import com.blaze.framework.core.util.uitls.AssertUtil;
import com.blaze.framework.core.util.uitls.ServletRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * 分页工具类
 *
 * @author created by Zhou Zongbo on 2025/5/29.
 */
@Slf4j
public class PageUtil {
    private PageUtil() {

    }

    /**
     * 默认分页-页数
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 默认分页-每页条数
     */
    public static final int DEFAULT_PAGE_SIZE = 10;
    /**
     * 分页-第几页
     */
    public static final String PAGE_NUM = "pageNum";
    /**
     * 分页-每页条数
     */
    public static final String PAGE_SIZE = "pageSize";
    public static final String ORDER_BY = "orderBy";
    /**
     * 升序排列
     */
    public static final String ASC = "asc";

    /**
     * 开启分页(从HttpRequestServlet)中获取分页信息
     * 从HttpServletRequest中
     */
    public static <T> Page<T> getPage() {
        int pageNum = getIntParameter(PAGE_NUM, DEFAULT_PAGE_NUM);
        int pageSize = getIntParameter(PAGE_SIZE, DEFAULT_PAGE_SIZE);
        AssertUtil.isTrue(pageNum > 0, "分页页数必须大于0");
        AssertUtil.isTrue(pageSize > 0, "分页每页条数必须大于0");

        String orderBy = ServletRequestUtils.getRequestParameter(ORDER_BY);

        Page<T> page = new Page<>(pageNum, pageSize);
        PageUtil.getOrderItem(orderBy).ifPresent(page::addOrder);
        return page;
    }

    private static int getIntParameter(String parameter, int defaultValue) {
        String requestParameter = ServletRequestUtils.getRequestParameter(parameter);
        if (StringUtils.isNotBlank(requestParameter)) {
            try {
                return Integer.parseInt(requestParameter);
            } catch (Exception ex) {
                log.warn("参数 {} 解析失败，使用默认值: {}", parameter, defaultValue);
            }
        }
        return defaultValue;
    }

    /**
     * 解析排序字段
     *
     * @param orderBy name,asc或则name,desc
     * @return Optional OrderItem
     */
    public static Optional<OrderItem> getOrderItem(String orderBy) {
        if (StringUtils.isNotBlank(orderBy)) {
            boolean check = SqlSafeUtil.check(orderBy);
            if (check) {
                throw new CheckedException("排序字段【" + orderBy + "】存在SQL注入的风险。");
            }

            String[] orderParts = orderBy.split(",");
            if (orderParts.length == 1) {
                String orderByColumn = orderParts[0];
                return Optional.of(OrderItem.asc(orderByColumn));
            } else if (orderParts.length >= 2) {
                String orderByColumn = orderParts[0];
                String orderBySort = orderParts[1].trim().toLowerCase();
                boolean isAsc = ASC.equals(orderBySort);
                OrderItem orderItem = isAsc ? OrderItem.asc(orderByColumn) : OrderItem.desc(orderByColumn);
                return Optional.of(orderItem);
            }
        }
        return Optional.empty();
    }
}
